﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;

namespace QstkCore.DataAccess
{
    /// <summary>
    /// Minimal CSV reader supporting the bare minimum.
    /// </summary>
    public class CsvReader2 : IDisposable
    {
        private const char FieldSeparator = ',';
        private readonly string[] columns;
        private readonly StreamReader sr;
        private string[] currentRow;

        public CsvReader2(string filePath) : this(new StreamReader(new BufferedStream(File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read), 262144)))
        {
        }

        private CsvReader2(StreamReader sr)
        {
            this.sr = sr;
            var readLine = sr.ReadLine();
            if (readLine != null) 
                columns = readLine.Split(FieldSeparator);
        }

        private string this[string column]
        {
            get
            {
                int index = GetColumnIndex(column);
                return currentRow[index];
            }
        }

        public void Dispose()
        {
            sr.Dispose();
        }

        public bool Read()
        {
            string line = sr.ReadLine();
            if (line == null) return false;
            currentRow = line.Split(FieldSeparator);
            return true;
        }

        private int GetColumnIndex(string column)
        {
            for (int i = 0; i < columns.Length; i++)
                if (columns[i] == column)
                    return i;
            throw new Exception("Unable to find column '" + column + "' in CSV.");
        }

        public DateTime GetDateTime(string columnName)
        {
            DateTime rowtime = DateTime.Parse(this[columnName], CultureInfo);
            return rowtime;
        }

        public float GetFloat(string columnName)
        {
            float price = float.Parse(this[columnName], CultureInfo);
            return price;
        }

        private static readonly CultureInfo CultureInfo = new CultureInfo("en-US");

        public IEnumerable<string[]> AsEnumerable()
        {
            while (Read())
                yield return currentRow;
        }
    }
}